<script
	lang="ts"
	setup
>
import { productListGet, productIdDelete,productStatusPut } from '@/api'
import FullHeightTable from '@/components/FullHeightTable.vue'
import SearchInput from '@/components/SearchInput.vue'
import SubHeader from '@/components/SubHeader.vue'
import { useRenderAction } from '@/hooks/useRenderActions'
import { productColumns } from '@/tableColumns/product'
import ProductStatusSelector from '@/components/ProductStatusSelector.vue'
import ProductDetail from '@/views/console/product/components/ProductDetail.vue'
import { Add12Regular } from '@vicons/fluent'
import type {IProductStatusPut} from '@/typed/request'
import { type DataTableProps, NIcon } from 'naive-ui'
import { useRouter } from 'vue-router'
const router = useRouter()
import { ref } from 'vue'

const table = ref()
const showDetail = ref(false)
const productId = ref<number | null>(null)
const showAddModal = ref<boolean>(false)
const currentItem = ref<any>({})
const filterPrams = ref({
	keyword: '',
	status:''
})
const showResetModal = ref(false)
const currentResetUser = ref<any>(null)

const tableProps = ref<DataTableProps>({
	scrollX: 1200,
	rowKey: (item) => item.id,
    columns: (productColumns || []).concat([
        {
            title: '操作',
            key: 'actions',
            width: 240,
            fixed: 'right',
            align: 'center',
            render: item => {
                // 根据状态决定显示的按钮
                const statusAction = item.status === 1 ?
                    {
                        label: '下架',
                        type: 'warning',
                        round: true,
                        size: 'small',
                        onClick: () => onUpdateStatus(item,0) // 假设这是下架操作
                    } :
                    {
                        label: '上架',
                        type: 'success',
                        round: true,
                        size: 'small',
                        onClick: () => onUpdateStatus(item,1) // 假设这是上架操作
                    };

                return useRenderAction([
                    {
                        label: '编辑',
                        type: 'primary',
                        round: true,
                        size: 'small',
                        onClick: () => onEdit(item)
                    },
                    statusAction, // 根据状态动态显示的按钮
                    {
                        label: '删除',
                        type: 'error',
                        round: true,
                        size: 'small',
                        onClick: () => onDelete(item)
                    },
                ]);
            }
        }
    ])
})

function onShowDetail(id: number) {
    console.log('id:',id)
    productId.value = id
	showDetail.value = true
}

function reloadTable() {
	showAddModal.value = false
	table.value.reload();
}

function onAdd() {
    router.push('/console/product/add') // 直接跳转
}

function onEdit(item: any) {
    router.push({
        path: '/console/product/add',
        query: {
            id: item.id
        }
    })
}

async function onUpdateStatus(item:any,status:number){
	let o = {
	    id:item.id,
		status
	};

	let smap = {
	    0:'下架',
		1:'上架'
	}
    const dialog = window.$dialog.warning({
        title: `确认${smap[status]}`,
        content: `确定要${smap[status]}商品"${item.title}"吗？`,
        positiveText: '确定',
        negativeText: '取消',
        loading: false,
        closeOnEsc: false,
        maskClosable: false,
        onPositiveClick: async () => {
            dialog.loading = true
            try {
                const { code } = await productStatusPut(o as IProductStatusPut)
                if (code === 200) {
                    window.$message.success(`${smap[status]}成功`)
                    table.value?.reload()
                    dialog.loading = false
                    return true
                }
                return false
            } catch (error) {
                window.$message.error(`${smap[status]}失败`)
                dialog.loading = false
                return false
            }
        }
    })
}

async function onDelete(item: any) {
	const dialog = window.$dialog.warning({
		title: '确认删除',
		content: `确定要删除商品"${item.title}"吗？`,
		positiveText: '确定',
		negativeText: '取消',
		loading: false,
		closeOnEsc: false,
		maskClosable: false,
		onPositiveClick: async () => {
			dialog.loading = true
			try {
				const { code } = await productIdDelete(item.id)
				if (code === 200) {
					window.$message.success('删除成功')
					table.value?.reload()
					dialog.loading = false
					return true
				}
				return false
			} catch (error) {
				window.$message.error('删除失败')
				dialog.loading = false
				return false
			}
		}
	})
}

function onResetPassword(item: any) {
	currentResetUser.value = item
	showResetModal.value = true
}

</script>

<template>

	<n-layout>
		<sub-header>
			<template #right>
				<ProductStatusSelector v-model:value="filterPrams.status"/>
				<SearchInput
					v-model:value="filterPrams.keyword"
					placeholder="商品标题"
					width="210"
				/>

				<n-button
					type="primary"
					@click="onAdd"
				>
					<template #icon>
						<n-icon>
							<Add12Regular/>
						</n-icon>
					</template>
					添加商品
				</n-button>
			</template>
		</sub-header>
		<n-layout class="content">
			<FullHeightTable
				ref="table"
				:params="filterPrams"
				:table-props="tableProps"
				:table-request="productListGet"
			/>
		</n-layout>
		<ProductDetail
			v-model:show="showDetail"
			:id="productId || 0"
			@update:list="reloadTable"
		/>
		<AddTenant
			v-model:show="showAddModal"
			:data="currentItem"
			@update:list="reloadTable"
		/>
		<ResetPassword
			v-model:show="showResetModal"
			:data="currentResetUser"
			@update:list="reloadTable"
		/>
	</n-layout>
</template>
<style
	lang="less"
	scoped
>
.content {
	padding: 0 20px 20px 20px;

	header {
		padding: 20px 0;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}
}
</style>
